package util

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/dgrijalva/jwt-go"
	"os"
	"strconv"
	"strings"
	"time"
)

func CheckToken(tokenString string) (userName string, err error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(beego.AppConfig.String("TokenSecrets")), nil
	})

	if err != nil {
		beego.Error(err)
		return "", err
	}
	if token != nil && token.Valid {
		claims, _ := token.Claims.(jwt.MapClaims)
		userName = claims["userName"].(string)
	}
	return userName, err
}

func CreateToken(userName string) (tokenString string, err error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	Tokenexp, err := strconv.Atoi(beego.AppConfig.String("Tokenexp"))
	if err != nil {
		return tokenString, err
	}
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(Tokenexp)).Unix()
	claims["iat"] = time.Now().Unix()
	claims["userName"] = userName
	token.Claims = claims
	tokenString, err = token.SignedString([]byte(beego.AppConfig.String("TokenSecrets")))
	if err != nil {
		fmt.Println("generate json web token failed !! error:", err)
		return tokenString, err
	}
	return tokenString, err
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func PathIsNotExistAndCreate(path string) error {
	_, err := os.Stat(path)
	if err == nil {
		return err
	}else{
		if os.IsNotExist(err) {
			return os.MkdirAll(path,os.ModePerm)
		}else{
			return nil
		}
	}
}

func IsSameDay(oldDay time.Time,newDay time.Time) bool {
	if oldDay.Year() != newDay.Year() || oldDay.Month() != newDay.Month() || oldDay.Day() != newDay.Day() {
		return false
	}else{
		return true
	}
}

func SetFirstToUpper(value string) string  {
	if len(value) < 1 {
		return ""
	}else{
		return strings.ToUpper(beego.Substr(value,0,1)) + beego.Substr(value,1, len(value) - 1)
	}
}

